function countIslands(grids) {
    var groups = [];
    for (var i = 0; i < grids.length; i++) {
        for (var j = 0; j < grids[0].length; j++) {
            if (grids[i][j] === 1) {
                var top_idx = groups.findIndex(v => v.includes(`${i - 1},${j}`));
                var left_idx = groups.findIndex(v => v.includes(`${i},${j - 1}`));
                var top_left_idx = groups.findIndex(v => v.includes(`${i - 1},${j - 1}`));
                var top_right_idx = groups.findIndex(v => v.includes(`${i - 1},${j + 1}`));
                if (top_idx > -1 && left_idx > -1) {
                    groups[top_idx] = groups[top_idx].concat(groups[left_idx]);
                    groups[top_idx].push(`${i},${j}`);
                    groups[top_idx] = [...new Set(groups[top_idx])];
                    if (left_idx != top_idx) groups.splice(left_idx, 1);
                    if (top_left_idx > -1 && top_left_idx != top_idx) groups.splice(top_left_idx, 1);
                    if (top_right_idx > -1 && top_right_idx != top_idx) groups.splice(top_right_idx, 1);
                }
                else if (top_idx > -1) groups[top_idx].push(`${i},${j}`);
                else if (left_idx > -1) {
                    groups[left_idx].push(`${i},${j}`);
                    var top_right_idx = groups.findIndex(v => v.includes(`${i - 1},${j + 1}`));
                    if (top_right_idx > -1 && top_right_idx != left_idx) groups.splice(top_right_idx, 1);
                }
                else if (top_left_idx > -1) groups[top_left_idx].push(`${i},${j}`);
                else if (top_right_idx > -1) groups[top_right_idx].push(`${i},${j}`);
                else groups.push([`${i},${j}`]);
            }
        }
    }
    return groups.length;
}
var image = [
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 1, 1, 0, 0, 0, 0, 0, 0],
    [0, 0, 1, 1, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
    [0, 0, 0, 0, 0, 1, 1, 1, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
];
countIslands(image)